﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace Himp.Platform
{
    /// <summary>
    /// 实例服务
    /// </summary>
    public class WorkflowInstanceService : PlatformAppService
    {
        private ActiviWorkflowManager _workflowManager;

        public WorkflowInstanceService(ActiviWorkflowManager workflowManager)
        {
            _workflowManager = workflowManager;
        }

        public async Task<PagedResultDto<WorkflowInstanceDto>> GetListAsync(WorkflowInstanceInput input)
        {
            string begntime = "";
            string endtime = "";

            if (!input.Begntime.HasValue)
            {
                begntime = DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                begntime = input.Begntime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            }

            if (!input.Endtime.HasValue)
            {
                endtime = DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                endtime = input.Endtime.Value.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
            }

            var list = await _workflowManager.GetProcessInstance(begntime, endtime, input.Status);
            var itemsDto = ObjectMapper.Map<List<WorkflowInstance>, List<WorkflowInstanceDto>>(list);

            if (input.Pi == 0)
            {
                return new PagedResultDto<WorkflowInstanceDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = itemsDto.Count();
                var pagedItems = itemsDto.Skip((input.Pi - 1) * input.Ps).Take(input.Ps);

                return new PagedResultDto<WorkflowInstanceDto>(totalCount, pagedItems.ToList());
            }
        }

        /// <summary>
        /// 启动流程实例
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<WorkflowInstanceDto> PostAsync(WorkflowInstanceStartDto input)
        {
            Dictionary<string, object> pars = new Dictionary<string, object>();
            var userId = "admin";
            Dictionary<string, List<string>> assocUsers = new Dictionary<string, List<string>>();

            await _workflowManager.StartWorkflowInstance(input.DeployKey, assocUsers, userId, input.Pars);

            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<WorkflowInstanceDto> PostFinishAsync(WorkflowInstanceExecDto input)
        {
            Dictionary<string, object> pars = new Dictionary<string, object>();
            var userId = "admin";
            await _workflowManager.FinishWorkflowInstance(input.WorkflowInstanceId, userId);

            return null;
        }
    }
}
